<script lang="ts" setup>
import type { ChatMessage } from "@/types/chat";
import { useChatStore } from "../../stores/chat";
import TabBar from "../index/components/tabBar/tabBar.vue";
import { chatWithKimi } from "./kimiChat";

const messageList = ref<ChatMessage[]>([]);

const inputMessage = ref("");

const scrollIntoView = ref("");

const isLoading = ref(false);

const scrollViewRef = ref<any>(null);

const onChangeInput = (val: any) => {
  inputMessage.value = val.detail.value;
};

const sendMessage = async () => {
  if (!inputMessage.value) return;

  // 添加用户消息
  const userMessage: ChatMessage = {
    id: Date.now(),
    content: inputMessage.value,
    isAI: false,
    timestamp: Date.now(),
  };
  useChatStore().addMessage(userMessage);

  messageList.value.push(userMessage);

  // 添加 AI 消息占位
  const aiMessageId = Date.now() + 1;

  const aiMessage: ChatMessage = {
    id: aiMessageId,
    content: "",
    isAI: true,
    timestamp: Date.now(),
  };

  messageList.value.push(aiMessage);

  // 清空输入
  const userInput = inputMessage.value;
  inputMessage.value = "";

  isLoading.value = true;
  scrollIntoView.value = `msg-${aiMessageId}`;

  try {
    // 调用 Kimi AI，使用 onProgress 回调
    await chatWithKimi(userInput, (text: string) => {
      const currentMsg = messageList.value.find(
        (msg) => msg.id === aiMessageId
      );
      if (currentMsg) {
        debugger;
        currentMsg.content += text;
        nextTick(() => {
          scrollToBottom();
        });
      }
    });
  } catch (error) {
    // 错误处理
    const errorMessage: ChatMessage = {
      id: Date.now(),
      content: "抱歉，发生了一些错误，请稍后重试。",
      isAI: true,
      timestamp: Date.now(),
    };
    messageList.value.push(errorMessage);
  } finally {
    isLoading.value = false;
  }
};

const scrollToBottom = () => {
  // scroll-view滚动到底部
  nextTick(() => {
    scrollViewRef.value.scrollTop = scrollViewRef.value.scrollHeight;
  });
};
</script>

<template>
  <view class="chat-page">
    <!-- 聊天内容区域 -->
    <scroll-view
      ref="scrollViewRef"
      scroll-y
      class="chat-container"
      :scroll-into-view="scrollIntoView"
      :scroll-anchoring="true"
      :scroll-with-animation="true"
      :enhanced="true"
      :show-scrollbar="false"
    >
      <!-- <view class="chat-content pb-5 pl-5 pr-5 h-full"> -->
      <view
        v-if="messageList.length === 0"
        class="flex items-center justify-center h-full text-gray-400 text-lg empty-hint"
      >
        开始和AI对话吧
      </view>
      <view
        v-else
        v-for="msg in messageList"
        :key="msg.id"
        :id="`msg-${msg.id}`"
        :class="['flex flex-col my-5', msg.isAI ? 'items-start' : 'items-end']"
      >
        <view
          :class="[
            'max-w-[70%] p-5 rounded-2xl break-all',
            msg.isAI ? 'bg-white text-gray-800' : 'bg-[#F5B642] text-white',
          ]"
        >
          <view
            v-if="msg.isAI && isLoading && !msg.content"
            class="flex space-x-2"
          >
            <view
              class="w-2 h-2 rounded-full bg-gray-400 animate-bounce"
              style="animation-delay: 0s"
            ></view>
            <view
              class="w-2 h-2 rounded-full bg-gray-400 animate-bounce"
              style="animation-delay: 0.2s"
            ></view>
            <view
              class="w-2 h-2 rounded-full bg-gray-400 animate-bounce"
              style="animation-delay: 0.4s"
            ></view>
          </view>
          <view v-else>{{ msg.content }}</view>
        </view>
      </view>
      <!-- </view> -->
    </scroll-view>

    <!-- 输入框区域 -->
    <view class="input-wrapper">
      <view class="input-container">
        <t-input
          v-model:value="inputMessage"
          class="flex-1 mr-3"
          placeholder="请输入消息..."
          :style="{ '--td-input-bg-color': '#f5f5f5' }"
          shape="round"
          @change="onChangeInput"
          @enter="sendMessage"
        />
        <t-button
          theme="primary"
          shape="round"
          size="small"
          class="w-[120rpx]"
          @tap="sendMessage"
          >发送</t-button
        >
      </view>
      <TabBar />
    </view>
  </view>
</template>

<style lang="scss">
page {
  height: 100vh;
}

.chat-page {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 162rpx);
  background-color: #f5f5f5;
  // height: 100vh;
  // padding-bottom: env(safe-area-inset-bottom);
}

.chat-container {
  padding: 20rpx;
  flex: 1;
  height: calc(100vh - 240rpx);
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  position: relative;
  display: flex;
  flex-direction: column;
}

.chat-content {
  min-height: 100%;
  position: relative;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.input-wrapper {
  // position: sticky;
  // bottom: 0;
  // left: 0;
  // right: 0;
  background: white;
  z-index: 1;
}

// .input-wrapper {
//   // position: fixed;
//   // bottom: 0;
//   // left: 0;
//   // right: 0;
//   background: white;
// }

.input-container {
  padding: 20rpx;
  background: white;
  border-top: 1px solid #eee;
  display: flex;
  align-items: center;
}

@keyframes bounce {
  0%,
  100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-5px);
  }
}

.animate-bounce {
  animation: bounce 1s infinite;
}
</style>
